<script setup>
import * as echarts from 'echarts';
import router from "../../../router/index.js";
import {listExchangeBinding, publishMessage, selectExchange} from "../../../http/rabbitmq/exchange.js";
import {onMounted, onUnmounted, ref} from "vue";
import {onBeforeRouteLeave, useRoute} from "vue-router";
import moment from "moment";
import {bindingExchangeQueue, unBindingExchangeQueue} from "../../../http/rabbitmq/binding.js";
import {listQueueByVhost} from "../../../http/rabbitmq/queue.js";
import {rabbitmqStore} from "../../../stores/counter.js";
import {ElMessage} from "element-plus";
import {Back} from "@element-plus/icons-vue";

const route = useRoute()

let chartInstance = null
const vhostQueueList = ref([])

const exchangeBindingTableData = ref([])
const exchangeQueueBindingForm = ref({
  "vhost": route.query.vhost,
  "source": route.query.name,
  "destination": "",
  "routing_key": "",
  "arguments": {},
})

const exchangeDetails = ref({})
const publishInDetails = ref({
  time: [],
  data: []
})
const publishOutDetails = ref({
  time: [],
  data: []
})

const showPublishMessageForm = ref(false)
const publishMessageForm = ref({
  "vhost": route.query.vhost,
  "name": "",
  "payload": "",
  "payload_encoding": "string",
  "routing_key": "",
  "properties": {},
})

const msgRates = ref("60_5")
const publishInRate = ref(0)
const publishOutRate = ref(0)

function handleShowPublishMessageForm(row) {
  publishMessageForm.value.routing_key = row.routing_key
  publishMessageForm.value.name = row.source
  showPublishMessageForm.value = true
}

function handlePublishMessage() {
  publishMessage(publishMessageForm.value).then(response => {
    if (response.routed) {
      ElMessage({
        message: '发送成功',
        type: 'success',
      })
    } else {
      ElMessage({
        message: '发送失败',
        type: 'error',
      })
    }
  })
}


function handleExchangeSelect() {
  selectExchange(route.query.vhost, route.query.name, msgRates.value).then(response => {
    exchangeDetails.value = response

    publishOutRate.value = parseInt(response.message_stats.publish_out_details.rate)
    publishOutDetails.value.time = []
    publishOutDetails.value.data = []
    let samples = response.message_stats.publish_out_details.samples.reverse()
    for (let i = 0; i < (samples.length - 1); i++) {
      let item = samples[i]
      let nextItem = samples[i + 1]
      publishOutDetails.value.data.push(parseInt(nextItem.sample) - parseInt(item.sample))
      publishOutDetails.value.time.push(item.timestamp)
    }

    publishInDetails.value.time = []
    publishInDetails.value.data = []
    if (response.message_stats.publish_in_details) {
      publishInRate.value = parseInt(response.message_stats.publish_in_details.rate)
      samples = response.message_stats.publish_in_details.samples.reverse()
      for (let i = 0; i < (samples.length - 1); i++) {
        let item = samples[i]
        let nextItem = samples[i + 1]
        publishInDetails.value.data.push(parseInt(nextItem.sample) - parseInt(item.sample))
        publishInDetails.value.time.push(item.timestamp)
      }
    }

    init()
  })
}

function init() {
  if (chartInstance == null) {
    chartInstance = echarts.init(document.getElementById('exchange_message_stats'))
    window.addEventListener("resize", function (){
      chartInstance.resize()
    })
  }
  const config = {
    title: {
      text: 'Message rates'
    },
    grid: {
      left: '5%',
      right: '1%',
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['publish_in_details', 'publish_out_details']
    },
    xAxis: {
      type: "category",
      data: publishOutDetails.value.time,
      axisLabel: {
        formatter: function (value, index) {
          return moment(parseInt(value)).format("yyyy-MM-DD HH:mm:ss").replace(' ', '\n')
        }
      }
    },
    yAxis: {},
    series: [
      {
        name: "publish_in_details",
        type: "line",
        data: publishInDetails.value.data
      },
      {
        name: "publish_out_details",
        type: "line",
        data: publishOutDetails.value.data
      }
    ]
  }
  chartInstance.setOption(config)
}

function handleExchangeBindingList() {
  listExchangeBinding(route.query.vhost, route.query.name).then(response => {
    exchangeBindingTableData.value = response
  })
}

function handleUnBindingExchangeQueue(data) {
  unBindingExchangeQueue(data).then(response => {
    handleExchangeBindingList(route.query.vhost, route.query.name)
  })
}

function handleBindingExchangeQueue() {
  bindingExchangeQueue(exchangeQueueBindingForm.value).then(response => {
    handleExchangeBindingList(route.query.vhost, route.query.name)
  })
}

function handleVhostQueueList() {
  listQueueByVhost(route.query.vhost).then(response => {
    vhostQueueList.value = response
  })
}

const goBack = () => {
  router.push({path: '/exchange'})
}

onMounted(() => {
  handleVhostQueueList()
  handleExchangeSelect()
  handleExchangeBindingList()
  rabbitmqStore().setTimer(handleExchangeSelect)
})

onUnmounted(() => {
  clearInterval(rabbitmqStore().timer)
  rabbitmqStore().deleteTimer()
})

onBeforeRouteLeave(() => {
  clearInterval(rabbitmqStore().timer)
  rabbitmqStore().deleteTimer()
})
</script>

<template>
  <el-page-header @back="goBack">
    <template #content>
      <span class="text-large font-600 mr-3"> {{ exchangeDetails.name }} </span>
    </template>
    <template #extra>
      <el-form ref="form" :inline="true" :model="msgRates" label-width="80px">
        <el-form-item label="时间区间">
          <el-select v-model="msgRates" style="width: 220px" clearable
                     @change="handleExchangeSelect()">
            <el-option
                v-for="item in rabbitmqStore().msgRates"
                :key="item.ukId"
                :label="item.name"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </template>
  </el-page-header>
  <div style="width: 100%; height: calc(100% - 60px); overflow: auto">
    <el-descriptions column="4">
      <el-descriptions-item label="vhost">：{{ exchangeDetails.vhost }}</el-descriptions-item>
      <el-descriptions-item label="type">：{{ exchangeDetails.type }}</el-descriptions-item>
      <el-descriptions-item label="auto_delete">：{{ exchangeDetails.auto_delete }}</el-descriptions-item>
      <el-descriptions-item label="durable">：{{ exchangeDetails.durable }}</el-descriptions-item>
      <el-descriptions-item label="internal">：{{ exchangeDetails.internal }}</el-descriptions-item>
      <el-descriptions-item label="publishInRate">：{{ publishInRate }}/s</el-descriptions-item>
      <el-descriptions-item label="publishInRate">：{{ publishOutRate }}/s</el-descriptions-item>
    </el-descriptions>
    <div id="exchange_message_stats" style="width: 100%; height: 300px">
      暂无数据
    </div>
    <el-form ref="form" :inline="true" :model="exchangeQueueBindingForm" label-width="80px">
      <el-form-item label="队列">
        <el-select v-model="exchangeQueueBindingForm.destination" style="width: 220px" clearable>
          <el-option
              v-for="item in vhostQueueList"
              :key="item.name"
              :label="item.name"
              :value="item.name">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="routing_key">
        <el-input v-model="exchangeQueueBindingForm.routing_key" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleBindingExchangeQueue">绑定队列</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="exchangeBindingTableData" border style="width: 100%;">
      <el-table-column prop="vhost" label="vhost" width="80"/>
      <el-table-column prop="source" label="source" width="280"/>
      <el-table-column prop="destination" label="destination" width="280"/>
      <el-table-column prop="routing_key" label="routing_key"/>
      <el-table-column label="operations" width="200" fixed="right">
        <template #default="scope">
          <el-button @click="handleShowPublishMessageForm(scope.row)">
            发送消息
          </el-button>
          <el-popconfirm
              width="230"
              hide-icon
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="handleUnBindingExchangeQueue(scope.row)"
              :title="'是否删除绑定队列 [ ' + scope.row.destination + ' ] ？'">
            <template #reference>
              <el-button type="danger">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <el-drawer v-model="showPublishMessageForm">
    <template #header>
      <h4>Publish Message</h4>
    </template>
    <template #default>
      <el-form ref="form" :model="publishMessageForm" label-width="160px">
        <el-form-item label="routing_key">
          <el-input v-model="publishMessageForm.routing_key"></el-input>
        </el-form-item>
        <el-form-item label="payload">
          <el-input
              v-model="publishMessageForm.payload"
              style="width: 100%"
              :autosize="{ minRows: 10, maxRows: 30 }"
              type="textarea"
              placeholder="Please input"
          />
        </el-form-item>
        <el-form-item label="payload_encoding">
          <el-select v-model="publishMessageForm.payload_encoding">
            <el-option
                v-for="item in rabbitmqStore().payloadEncoding"
                :key="item.name"
                :label="item.name"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handlePublishMessage">Publish Message</el-button>
          <el-button @click="showPublishMessageForm = false">Cancel</el-button>
        </el-form-item>
      </el-form>
    </template>
  </el-drawer>

</template>

<style scoped>

</style>